#include "../glutil/GLee.h"
#include "sky.h"
#include "math.h"
#include <QImage>
Sky::Sky()
{

}

void Sky::draw(float brightness)
{
    drawSky(41,20,20, brightness);
}


Point3D Sky::getSegmentedCirclePoint(float heightAngle, float radius, int segments, int currentPoint)
{
    Point3D p;
    p.z = radius * cos(heightAngle);

    float localRadius = radius*sin(heightAngle); 
    float angle = 2*M_PI/segments * currentPoint;
    
    p.x = localRadius * cos(angle);
    p.y = localRadius * sin(angle);

    return p;
}

void Sky::interpolateColors(const float * c1, const float * c2, float * result, float interpValue)
{
    float u = interpValue;
    float v = 1-interpValue;
    result[0] = v*c1[0]+u*c2[0];
    result[1] = v*c1[1]+u*c2[1];
    result[2] = v*c1[2]+u*c2[2];
}

void Sky::getColorByAngle(float angle, float * color, float brightness)
{
    float topColor[3]={1.0,0.6,2.0};
    float horizColor[3]={1.7,1.2,0.9};
    float groundColor[3] = {0.3,0.2,0.2};

    if(angle>M_PI/2)
    {
    // Si el angulo es positivo, interpolar despacio del color horizonte al color cielo
        interpolateColors(horizColor,topColor,color,angle-M_PI/2);
    }
    else
    {
    // Si el angulo es negativo, interpolar rápido del color horizonte al color verde
        interpolateColors(horizColor,groundColor,color,angle/2);
    }
	color[0]*= brightness;
	color[1]*= brightness;
	color[2]*= brightness;
}

void Sky::drawSky(float radius, int segmentsPerCircle, int heightSections, float brightness)
{
	glPushMatrix();
    glTranslatef(0,4,0);
    GLfloat tempColor[4]={0.0,0.0,0.0,0.0};
    // We draw the surrounding quads
    for(int i=0; i<heightSections;++i)
    {
        glBegin(GL_QUAD_STRIP);
            for(int j=0;j<=segmentsPerCircle;++j)
            {
                Point3D p1 = getSegmentedCirclePoint(M_PI*i/heightSections,radius,segmentsPerCircle,j);
                getColorByAngle(M_PI*i/heightSections,tempColor, brightness);
                glColor4fv(tempColor);

                glTexCoord2f(p1.x/10.0,p1.y/10.0); 
                glVertex3f(p1.x,p1.z, p1.y);

                Point3D p2 = getSegmentedCirclePoint(M_PI*(i+1)/heightSections,radius,segmentsPerCircle,j);
                getColorByAngle(M_PI*(i+1)/heightSections,tempColor,brightness);
                glColor4fv(tempColor);
                glTexCoord2f(p2.x/10.0,p2.y/10.0); 
                glVertex3f(p2.x,p2.z, p2.y);
            }
        glEnd();
    }
	glPopMatrix();
}

void Sky::cleanUp()
{
}


